package rmi.chat.server;

import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.*;

import rmi.chat.client.*;


public class ChatServer extends UnicastRemoteObject implements Server {
	private ArrayList allClients = new ArrayList(100);
	public ChatServer() throws RemoteException{
		super();
	}
	
	public void addReceiver(Receiver client) throws RemoteException{
		allClients.add(client);
		System.out.println("Added a client...");
	}
	
	@Override
	synchronized public void broadcast(String msg) throws RemoteException{
		int count = allClients.size();
		System.out.println("현재 접속중인 클라이언트 ::: " + count);
		Receiver client = null;
		for(int i=0; i<count; i++){
			client = (Receiver)allClients.get(i);
			client.printMsg(msg);
		}
	}
	
	synchronized public void removeReceiver(Receiver client) throws RemoteException{
		allClients.remove(allClients.indexOf(client));
	}
	
	public static void main(String[] args){
		try{
			Server server = new ChatServer();
			Runtime.getRuntime().exec("rmiregistry 2000");
			LocateRegistry.createRegistry(2000);
			Naming.rebind("rmi://localhost:2000/ChatServer", server);
			System.out.println("Remote Object[" + Server.CHAT_SERVER + "] bound... on port 2000");
		}catch(Exception e) {
			System.err.println("RMI 서버 생성시 오류 발생 ::: " + e);
			System.exit(1);
		}
	}
}
